//
//  HeaderWeekView.swift
//  koolcar
//
//  Created by xiantian on 2023/10/24.
//

import UIKit
//typealias HeaderWeekViewBlock = (CalendarItemData)->Void
class HeaderWeekView: UIView {
//    var selectBlock: HeaderWeekViewBlock?
    var collectionView: UICollectionView!
//    var dataArray: [CalendarItemData] = []
    private var bkgView: UIView!
    ///选中的日期，默认当天
    ///var selectDate: String = ""
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = Theme.viewBkgGrayColor
        bkgView = UIView()
        bkgView.backgroundColor = .white
        self.addSubview(bkgView)
        
        let layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize.init(width: (kScreenWidth - 28) / 7, height: 54)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        self.collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 54), collectionViewLayout: layout)
        self.collectionView.register(WeekCell.self, forCellWithReuseIdentifier: "WeekCell")
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = UIColor.white
        self.collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 14, bottom: 0, right: 14)
        self.collectionView.showsHorizontalScrollIndicator = false
        self.collectionView.isScrollEnabled = false //不滑动
        bkgView.addSubview(self.collectionView)
        
        self.addSnpLayout()
        //self.loadData()
    }
    
    private func addSnpLayout(){
        bkgView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
    }
    
    func refreashLoadData(){
        self.collectionView.reloadData()
//        let selectItem = self.dataArray.first(where: {$0.select == true})
        if selectItem != nil{
            //有选中状态时，滑动到选中日期
            self.scrollToItem(dateStr: selectItem?.date ?? "")
        }else{
            //默认进来时没有选中的状态，要滑动到当前的日期
            let curDate = XTManageCenter.getDateStringNow()
            self.scrollToItem(dateStr: curDate)
        }
    }
    
    private func scrollToItem(dateStr: String){
        let weekStartDate = XTManageCenter.getCurrentDateInWeekStart(date: dateStr)
//        let startIndex = self.dataArray.firstIndex(where: {$0.date == weekStartDate})
        if self.dataArray.count > startIndex ?? 0 {
            DispatchQueue.main.async {
                self.collectionView.scrollToItem(at: IndexPath.init(row: startIndex ?? 0, section: 0), at: .left, animated: true)
            }
        }
    }
    
    @objc func handlePan(pan: UIPanGestureRecognizer){
        if pan.state == .ended {
            var tempH: CGFloat = 81
            if self.frame.size.height > 160 {
                //展开
                tempH = 270
            }else{
                //收起
                tempH = 91
                
            }
            UIView.animate(withDuration: 0.24) {
                self.frame.size.height = tempH
            }
        }else{
            // 获取拖拽手势的位置
            let translation = pan.translation(in: self.viewController().view!)
            
            // 将视图的中心点设置为手势位置加上初始位置
            let tempHeight = self.frame.size.height + translation.y
            self.frame.size.height = max(tempHeight, 81)
            // 重置手势的位置
            pan.setTranslation(CGPoint.zero, in: self.viewController().view!)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension HeaderWeekView: UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WeekCell", for: indexPath) as! WeekCell
        if self.dataArray.count > indexPath.row {
            let itemModel = self.dataArray[indexPath.row]
            cell.titleLab.text = itemModel.weekday
            cell.subTitleLab.text = itemModel.day
           
            if itemModel.select {
                cell.backgroundColor = UIColor.init(hex: 0x71D883, alpha: 0.3)
            }else{
                cell.backgroundColor = .white
            }
            if itemModel.enable ?? false {
                cell.titleLab.textColor = Theme.titleLabColor
                cell.subTitleLab.textColor = Theme.titleLabColor
            }else{
                cell.titleLab.textColor = Theme.lightNineColor
                cell.subTitleLab.textColor = Theme.lightNineColor
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard self.dataArray.count > indexPath.row else {
            return
        }
        let item = self.dataArray[indexPath.row]
        guard item.enable ?? false else {
            return
        }
        self.selectBlock?(item)
    }
}


